﻿using System;
using System.Collections.Generic;

namespace _01_CompositeModel_Basic
{
    class Program
    {
        static void Main(string[] args)
        {
            // 生成根，根上长出两个叶子
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            // 根上长出分支，分支上也有两个叶子
            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            root.Add(comp);

            // 在Composite X上再长出分支，也有两个叶子
            Composite comp2 = new Composite("Composite XY");
            comp2.Add(new Leaf("Leaf XYA"));
            comp2.Add(new Leaf("Leaf XYB"));
            comp.Add(comp2);

            // 根部又长出两叶子
            root.Add(new Leaf("Leaf C"));
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);

            // 显示大树样子
            root.Display(1);

            Console.Read();
        }
    }

    // 组成抽象类
    abstract class Component
    {
        protected string name;
        public Component(string name)
        {
            this.name = name;
        }
        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int depth);
    }

    // 叶节点
    class Leaf : Component
    {
        public Leaf(string name) : base(name) { }
        public override void Add(Component c)
        {
            Console.WriteLine("cannot add to a leaf");
        }
        public override void Remove(Component c)
        {
            Console.WriteLine("cannot remove to a leaf");
        }
        public override void Display(int depth)
        {
            Console.WriteLine(new string('-',depth)+name);
        }
    }

    // 枝节点
    class Composite : Component
    {
        private List<Component> children = new List<Component>();
        public Composite(string name) : base(name) { }
        public override void Add(Component c)
        {
            children.Add(c);
        }
        public override void Remove(Component c)
        {
            children.Remove(c);
        }
        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + name);

            foreach (Component item in children)
            {
                item.Display(depth + 2);
            }
        }
    }
}
